import React, { useState, useEffect } from 'react'
import { SearchBar, Toast, Tag, Dialog } from 'antd-mobile' // 组件
import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate, history } from 'umi'
import { ProductLists } from "@/api"; // 接口
import Icon from '@/components/icon/index'
import './assets/style.scss'

export default function index() {
  const navigate = useNavigate()
  /* 模糊搜索弹出关键字 历史记录存到缓存*/
  const [historyList, setHistoryList] = useState<Array<any>>([])
  const searchChange = (k: string) => { // 输入框回车时触发 返回当前输入框的值
    if (!historyList.includes(k)) {
      localStorage.setItem('history',[...historyList,k].reverse().join(','))
      setHistoryList([...historyList,k].reverse())
    } 

    ProductLists({ // 模糊搜索 请求
      k
    }).then((res: any) => {
      if (res.data.code === 0) { // 携带分类id 跳转到 分类列表页 
        navigate('/productPage', {state: {
          id: res.data.data.result[0].categoryId
        }})
      }
      if (res.data.code === 700) {
        Toast.show({
          content: res.data.msg
        })
      }
    })
  }
  /* useState 钩子 */
  useState(() => {
    if(localStorage.getItem('history')) { //初始化 存储 缓存中历史记录 
      setHistoryList(localStorage.getItem('history').split(','))
    }
  },[])
  /* 动态渲染 返回的 */
  return (
    <div className="findBox">
      <div className="headerFind">
        <LeftOutline fontSize={24} onClick = {() => navigate('/home')}/>
        <SearchBar 
          placeholder='请输入内容' 
          showCancelButton 
          clearOnCancel 
          clearable
          onSearch={(findValue) => { // 输入框回车时触发
            searchChange(findValue)
          }}
          />
      </div>
      {/* 垃圾桶 */}
      <div className="clearBox">
          <h1 style={{color: 'red', fontSize: '15PX'}}>最近搜索</h1>
          <div onClick={
            async () => { // 点击垃圾桶 弹出确认框
              const result = await Dialog.confirm({
                content: '确定要清空吗?',
              })
              if (result) {
                localStorage.removeItem('history') // 清除 缓存历史记录
                history.go(0) // 刷新页面
              }
            }
            
          }>
            {
              localStorage.getItem('history')
              &&
              <Icon name='lajitong'/>
            }
          </div>
      </div>
      {/* 渲染 历史记录 */}
      <div className="history">
          {
            historyList.length
            ?
            historyList.map((element: string) => (
              <Tag key={element} style={{marginRight: '5PX',marginBottom: '5px', color: 'black'}} color='#F1F6F7'>{element}</Tag>
            ))
            :
            <span>暂无历史记录</span>
          }
      </div>
    </div>
  )
}
